package com.pesking.core.sqlparser.processor;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;

public class TimestampSqlParameterHandler extends SqlParameterProcessor {

	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"TS","TIMESTAMP"});
	}

	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		sbSQL.append("?");
		processors.add(sqlParameter);
	}

	@Override
	public void setParameter(PreparedStatement ps, Parameter parameter, int index,SqlParameter sqlParameter) throws SQLException {
		String value = parameter.getParameter(sqlParameter.getName());
		if (StringUtils.isBlank(value) || "null".equals(value)) {
			ps.setNull(index, java.sql.Types.TIMESTAMP);
		}
		else {
			String []pattern = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd HH","yyyy-MM-dd"};
			Date objValue = null;
			for(int n = 0 ; n < pattern.length ; n++){
				SimpleDateFormat sdf = new SimpleDateFormat(pattern[n]);
				
				try	{						
					objValue= sdf.parse(value);
					break;
				}
				catch(Exception ex)	{
					
				}
			}
			
			if (objValue == null){
				throw new SQLException("日期格式化错误");
			}
			ps.setTimestamp(index, new java.sql.Timestamp(objValue.getTime()));
		}
	}

}
